Scroll Progress Bar

Matrix Multiplication

Matrix multiplication is a mathematical operation that involves multiplying two matrices to produce a new matrix. In order to perform matrix multiplication, the number of columns in the first matrix should be equal to the number of rows in the second matrix.

Usage and Approach:

To perform matrix multiplication in C, use nested loops to traverse through the rows and columns of the matrices and calculate the corresponding elements of the resulting matrix.

Sample Code with Explanation and Output:

#include <stdio.h>

#define ROW_A 2
#define COL_A 3
#define ROW_B 3
#define COL_B 2

void matrixMultiplication(int A[][COL_A], int B[][COL_B], int C[][COL_B]) {
    for (int i = 0; i < ROW_A; i++) {
        for (int j = 0; j < COL_B; j++) {
            C[i][j] = 0;
            for (int k = 0; k < COL_A; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

void displayMatrix(int mat[][COL_B], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int matrixA[ROW_A][COL_A] = {{1, 2, 3}, {4, 5, 6}};
    int matrixB[ROW_B][COL_B] = {{7, 8}, {9, 10}, {11, 12}};
    int resultMatrix[ROW_A][COL_B];

    // Perform matrix multiplication
    matrixMultiplication(matrixA, matrixB, resultMatrix);

    printf("Matrix A:\n");
    displayMatrix(matrixA, ROW_A, COL_A);

    printf("Matrix B:\n");
    displayMatrix(matrixB, ROW_B, COL_B);

    printf("Resultant Matrix (A * B):\n");
    displayMatrix(resultMatrix, ROW_A, COL_B);

    return 0;
}
Output:

Matrix A:
1 2 3 
4 5 6 
Matrix B:
7 8 
9 10 
11 12 
Resultant Matrix (A * B):
58 64 
139 154 
Explanation:
  • In the sample code, have two matrices matrixA and matrixB of sizes 2x3 and 3x2, respectively.
  • The matrixMultiplication function performs the matrix multiplication operation and stores the result in resultMatrix.
  • Use nested loops to iterate over the rows and columns of both matrices and compute the corresponding elements of the result matrix using the formula for matrix multiplication.
  • The displayMatrix function is used to print the elements of a matrix in a readable format.
  • In the main function, display the input matrices matrixA and matrixB, and then the resultant matrix after matrix multiplication.
  • The output shows the input matrices matrixA and matrixB, followedby the resultant matrix obtained after performing the matrix multiplication operation (A * B).

What is the result of multiplying two matrices together in C?


Matrix

What is the operation used for matrix multiplication in C?


Multiply

What is the time complexity of matrix multiplication in C?


Cubic